import { request } from '../../utils/request';
Page({
  data: {
    activeTab: 0, // 默认选中"全部"标签
    orderList:[],
    filteredOrders: [], // 用于存储过滤后的订单
    isLoading:false
  },


  onLoad(options) {
    const tab = Number(options.tab);
    this.setData({
      activeTab: tab
    });
    this.getOrderList()
  },

  async getOrderList(){
    const res = await request("/greenold-order/order/orderInfo",{},'GET')
    res.rows = res.rows.map(row => {
      row.serviceActor = row.serviceActor.join(',');
      return row;
    });
    this.setData({
      orderList:res.rows,
    })
    console.log(this.data.orderList)
    this.addDetailProperty();
    // 初始加载时过滤订单
    this.filterOrders();
  },


  addDetailProperty(){
    const orderList = this.data.orderList;
    const newOrderList = orderList.map(order => {
      if(order.orderStatus === "0"){  //待支付
        return {
          ...order,
          status:"待支付",
          priceType: "应付", 
          statusClass: "status-pending",
          showCancel:true,
          showPay:true,
          showRefund:false,
          showDelete:false,
          cancelText:"取消订单",
          payText:"去支付",
          cancelBtnClass:"btn-pay" 
        };
      }else if(order.orderStatus === "1"){ //待执行
        return {
          ...order,
          status:"待执行",
          priceType: "实付", 
          statusClass: "status-processing",
          showCancel:false,
          showPay:false,
          showRefund:true,
          showDelete:false,
          refundText:"退款",
          refundBtnClass:"btn-refund" 
        };
      }else if(order.orderStatus === "2"){ //已执行
        return {
          ...order,
          status: "已执行",
          priceType: "实付", 
          statusClass: "status-executed",
          showCancel:false,
          showPay:false,
          showRefund:false,
          showDelete: true,
          deleteText:"删除",
          deleteBtnClass:"btn-delete" 
        };
      }else if(order.orderStatus === "3"){ //已完成
        return {
          ...order,
          status:"已完成",
          priceType: "实付", 
          statusClass: "status-completed",
          showCancel:false,
          showPay:false,
          showRefund:false,
          showDelete:true,
          deleteText:"删除",
          deleteBtnClass:"btn-delete" 
        };
      }else if(order.orderStatus === "4"){ //已关闭
        return {
          ...order,
          status:"已关闭",
          priceType: "应付", 
          statusClass: "status-closed",
          showCancel:false,
          showPay:false,
          showRefund:false,
          showDelete:true,
          deleteText:"删除",
          deleteBtnClass:"btn-delete" 
        };
      }else if(order.orderStatus === "5"){ //已退款
        return {
          ...order,
          status:"已退款",
          priceType: "实付", 
          statusClass: "status-refunded",
          showCancel:false,
          showPay:false,
          showRefund:false,
          showDelete:true,
          deleteText:"删除",
          deleteBtnClass:"btn-delete" 
        };
      }else{
        return {
          visible:"1"
        }
      }
    })
    this.setData({
      orderList:newOrderList
    })
  },

  //跳转到reason页面
  goToReason(event) {
    const id = event.currentTarget.dataset.id;
    const status = event.currentTarget.dataset.status;
    // 1. 跳转到普通页面（保留当前页）
    wx.navigateTo({
      url: `/pages/order-reason/order-reason?id=${id}&orderStatus=${status}` 
    })
  },

  //跳转到订单详情页面
  goToDetail(e) {
    // 获取传递的item对象
    const item = e.currentTarget.dataset.item;
    // 将对象转为JSON字符串（避免参数丢失）
    const itemStr = JSON.stringify(item);
    //跳转
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?item=${encodeURIComponent(itemStr)}` // 目标页面路径，必须以 / 开头
    })
  },

  // 切换标签
  switchTab(e) {
    // 获取点击的标签索引
    const index = Number(e.currentTarget.dataset.index); 
    // 更新选中的标签
    this.setData({
      activeTab: index
    }, () => {
      // 标签更新后过滤订单
      this.filterOrders();
    });
  },

  // 根据选中的标签过滤订单
  filterOrders() {
    const { activeTab, orderList } = this.data;
    let filtered;
    
    // 根据不同标签索引过滤不同状态的订单
    switch(activeTab) {
      case 0: // 全部
        filtered = orderList.filter(order => order.visible === "0")
        break;
      case 1: // 待支付
        filtered = orderList.filter(order => order.orderStatus === "0" & order.visible === "0");
        break;
      case 2: // 待执行
        filtered = orderList.filter(order => order.orderStatus === "1" & order.visible === "0");
        break;
      case 3: // 已执行
        filtered = orderList.filter(order => order.orderStatus === "2" & order.visible === "0");
        break;
      case 4: // 已完成
        filtered = orderList.filter(order => order.orderStatus === "3" & order.visible === "0");
        break;
      default:
        filtered = orderList;
    }
    // 更新过滤后的订单数据
    this.setData({
      filteredOrders: filtered
    });
  },

  // 取消订单
  handleCancel(e) {
    const id = e.currentTarget.dataset.id;
    // 实现取消订单逻辑
    wx.showToast({
      title: `取消订单 ${id}`,
      icon: 'none'
    });
  },

  // 去支付
  handlePay(e) {
    // const id = e.currentTarget.dataset.id;
    // const amount = e.currentTarget.dataset.amount;
    // const elderId = e.currentTarget.dataset.eid;
    // const payload = {
    //   id:id,
    //   amount:amount,
    //   serviceElderId:elderId
    // }
    // console.log(payload)
    // // 实现支付逻辑
    // wechatPay.call(this, payload)
    const orderNo = e.currentTarget.dataset.bizOrderNo
    const amount = e.currentTarget.dataset.amount
    console.log("订单号",orderNo)
    console.log("价格",amount)
    wx.navigateTo({
      url: `/pages/ready-pay/ready-pay?&orderNo=${orderNo}&amount=${amount}`
  });
  },

  // 退款
  handleRefund(e) {
    const id = e.currentTarget.dataset.id;
    // 实现退款逻辑
    wx.showToast({
      title: `退款订单 ${id}`,
      icon: 'none'
    });
  },

  // 删除
  handleDelete(e) {
    const id = e.currentTarget.dataset.id;
    wx.showModal({
      title: '确认删除',
      content: '您确定要删除该订单吗？',
      success: (res) => {
        if (res.confirm) {
          const deleteData = { 
            id,
            visible: 1
          };
          // 异步接口请求
          request("/greenold-order/order", deleteData, 'PUT').then(result => {
            if (result.code === 200) {
              wx.showToast({ title: '删除成功', icon: 'none' });
            } else {
              wx.showToast({ title: '删除失败', icon: 'none' });
            }
            // 关键：接口请求完成后，再查询最新数据
            this.getOrderList(); 
          }).catch(error => {
            // 补充异常处理（如网络错误）
            wx.showToast({ title: '请求失败', icon: 'none' });
            this.getOrderList(); // 可选：失败时也刷新一次
          });
        }
      }
    });
  }
});